package com.bitcarton.disso.core.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wwd
 */
public final class CookieUtil {


    public static Cookie get(HttpServletRequest request, String key) {
        Cookie[] cookiesArray = request.getCookies();
        if (cookiesArray != null && cookiesArray.length > 0) {
            for (Cookie cookie : cookiesArray) {
                if (cookie.getName().equals(key)) {
                    return cookie;
                }
            }
        }
        return null;
    }


    public static String getValue(HttpServletRequest request, String key) {
        Cookie cookie = get(request, key);
        if (cookie != null) {
            return cookie.getValue();
        }
        return null;
    }

    public static void remove(HttpServletRequest request, HttpServletResponse response, String key) {
        Cookie cookie = get(request, key);
        if (cookie != null) {
            set(response, key, "", null, "/", 0, true);
        }
    }

    private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) {
        Cookie cookie = new Cookie(key, value);
        if (domain != null) {
            cookie.setDomain(domain);
        }
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        cookie.setHttpOnly(isHttpOnly);
        response.addCookie(cookie);
    }

    public static void setCookie(HttpServletResponse response, String key, String value, int maxValue, String path, boolean isHttpOnly) {
        set(response, key, value, null, path, maxValue, isHttpOnly);
    }

    public static void setCookie(HttpServletResponse response, String key, String value, int maxValue, String path, boolean isHttpOnly, String domains) {
        set(response, key, value, domains, path, maxValue, isHttpOnly);
    }
}
